/****************
 *@description:  公告栏配置   
 *@author: Xhd
 *@API: 方子奥
 *@date: 2024-01-05 17:57:01
 *@version: V1.0.0
*************************************************************************/

import React, { useEffect, useState, useRef } from 'react';
import { Form, Input, Modal, Select, Switch } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons"
import TheQueryForm from "@/components/TheQueryForm";
import TheTable from "@/components/TheTable";
import ThePagination from '@/components/ThePagination';
import TheButton from "@/components/TheButton";
import { apiAnnouncementBoardConfiguration, apiAnnouncementBoardConfigurationAdd, apiAnnouncementBoardConfigurationUpdate, apiAnnouncementBoardConfigurationDelect, apiGetDictionariesValueByType } from "@/request/bulletinBoard/index.js";
import { apiGetAboutUsList } from '@/request/configuration';

const BulletinBoard = () => {
  let queryFormRef = useRef()
  const options = [
    { field: 'location', label: '位置', placeholder: '全部', required: false, rules: [], type: 'Select', options: [], txt: "name", values: "value", api: apiGetDictionariesValueByType, params: { type: "announcement_board_configuration_location" } },
    { field: 'announcementBoardName', label: '名称', placeholder: '名称', required: false, rules: [], type: 'Input', defaultValue: '' },
  ]
  const columns = [
    {
      title: '公告名称（标题）',
      dataIndex: 'announcementBoardName',
      key: 'announcementBoardName',
      align: 'center'
    },
    {
      title: '位置',
      dataIndex: 'location',
      key: 'location',
      align: 'center',
      render(text) {
        const arr = {
          homePage: "APP首页", shoppingCart: "购物车", confirmAn0rder: "确认订单页", chatList: "信息列表", dialogBox: "私聊对话框", giftPopUp: "礼物弹窗", rechargePopUp: "充值弹窗", H5Recharge: "充值H5页面", myPocket: "我的口袋"
        }
        let location = text.split(',').map((i, l) => {
          if (text.split(',').length === l + 1) {
            return arr[i]
          } else {
            return arr[i] + "、"
          }
        })
        return location
      }
    },
    {
      title: '备注',
      dataIndex: 'txt',
      key: 'txt',
      align: 'center'
    },
    {
      title: '开关',
      dataIndex: 'type',
      key: 'type',
      align: 'center',
      render(text, record, index) {
        return <Switch key={index + record.announcementBoardName} defaultChecked={text === 1 ? true : false} onChange={(checked) => open(checked, record.announcementBoardConfigurationId)} ></Switch>
      }
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center'
    },
    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      align: 'center',
      render(text, record) {
        return <div>
          <TheButton haspermi={["settings:bulletinBoard:edit"]} type="link" onClick={() => openModal("edit", record)} >修改</TheButton>
          <TheButton haspermi={["settings:bulletinBoard:del"]} type="link" onClick={() => bulletinDelete(record.announcementBoardConfigurationId)} >删除</TheButton>
        </div>
      }
    },
  ]
  const [dataSource, setDataSource] = useState([])
  const [queryForm, setQueryForm] = useState()
  const [pageData, setPageData] = useState({ pageNo: 1, pageSize: 10 })
  const [total, setTotal] = useState(0)
  const [range, setRange] = useState(1)
  const [title, setTitle] = useState("")
  const [visible, setVisible] = useState(false)
  const [announcementBoardConfigurationId, setAnnouncementBoardConfigurationId] = useState(null)
  const [location, setLocation] = useState([])
  const [jump, setJump] = useState([])
  const [initialValues, setInitialValues] = useState()

  useEffect(() => {
    getData({ ...pageData })
    getLocation()
    getJumpList()
  }, [])

  const getLocation = async () => {
    await apiGetDictionariesValueByType({ type: "announcement_board_configuration_location" }).then(res => {
      if (res.code === 0) {
        let data = res.data.map(i => {
          return { value: i.value, label: i.name }
        })
        setLocation(data)
      }
    })
  }
  const onFinishFailed = (errorInfo) => {
    const flag = errorInfo.values.announcementBoardName.length < 101 && errorInfo.values.announcementBoardName.length > 1
    if(!flag){
      React.$message({
        type: "error",
        content: '公告名称（标题）须在2-100字符之间'
      })
    }
  };

  const getJumpList = async () => {
    await apiGetAboutUsList().then(res => {
      if (res.code === 0) {
        let jump = [{ value: "-1", label: "不跳转" }]
        res.data.map(i => {
          jump.push({ value: i.aboutUsId, label: i.aboutUsTitle })
        })
        setJump(jump)
      }
    })
  }

  const getData = async (values) => {
    await apiAnnouncementBoardConfiguration(values).then(res => {
      if (res.code === 0) {
        if (res.data.length === 0) {
          // pageChange(values.pageNo-1, values.pageSize)
        }
        setDataSource(res.data)
        setTotal(res.totalCount)
        setRange(res.totalPage)
      }
    })
  }

  const onFormSearch = (values) => {
    getData({ pageNo: 1, pageSize: 10, ...values }).then(() => {
      setQueryForm(values)
    })
  }

  const onReset = () => {
    getData({ pageNo: 1, pageSize: 10 }).then(() => {
      setQueryForm(null)
    })
  }

  const pageChange = (pageNo, pageSize) => {
    setPageData({ pageNo, pageSize })
    getData({ pageNo, pageSize, ...queryForm })
  }

  const open = async (checked, announcementBoardConfigurationId) => {
    let type = 0
    if (checked) {
      type = 1
    }
    await apiAnnouncementBoardConfigurationUpdate({ type, announcementBoardConfigurationId }).then(res => {
      if (res.code === 0 && res.success) {
        React.$message({
          type: "success",
          content: type === 1 ? "已开启" : "已关闭"
        })
      }
    })
  }

  const bulletinDelete = (announcementBoardConfigurationId) => {
    Modal.confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      content: '确认删除该公告吗？',
      onOk: async () => {
        await apiAnnouncementBoardConfigurationDelect({ announcementBoardConfigurationId }).then(res => {
          if (res.code === 0 && res.data) {
            if( dataSource.length === 1 ){
              setPageData({
                pageNo: pageData.pageNo - 1,
                pageSize: 10
              })
            }
            getData({ pageNo: pageData.pageNo - 1, pageSize: 10, ...queryForm })
          }
        })
      }
    })
  }

  const openModal = (type, data) => {
    if (type === "add") {
      setTitle("新增页面")
      setInitialValues(null)
    } else {
      setTitle("编辑页面")
      setAnnouncementBoardConfigurationId(data.announcementBoardConfigurationId)
      let viewData = { ...data }
      viewData.location = viewData.location.split(',')
      setInitialValues(viewData)
    }
    setVisible(true)
  }

  const onFinish = async (values) => {
    values.location = values.location.toString()
    if (title === "新增页面") {
      await apiAnnouncementBoardConfigurationAdd(values).then(res => {
        if (res.code === 0) {
          React.$message({
            type: "success",
            content: "添加成功"
          })
        }
      })
    } else {
      await apiAnnouncementBoardConfigurationUpdate({ announcementBoardConfigurationId, ...values }).then(res => {
        if (res.code === 0) {
          React.$message({
            type: "success",
            content: "修改成功"
          })
        }
      })
    }
    setVisible(false)
    getData({ ...pageData, ...queryForm })
  }

  return (<div className='p-layout-box'>
    <TheQueryForm ref={(ref) => queryFormRef = ref} show={true} option={options}
      onReset={() => onReset()}
      onGetValues={(values) => onFormSearch(values)} />
    <div style={{ display: "flex", margin: "5px" }} >
      <span style={{ marginRight: "auto", fontWeight: 600 }}>公告配置</span>
      <TheButton haspermi={["settings:bulletinBoard:add"]} type="primary" size="moddle" onClick={() => openModal("add", null)}  >新增</TheButton>
    </div>
    <TheTable columns={columns} dataSource={dataSource} />
    <ThePagination
      pageNo={pageData.pageNo}
      pageSize={pageData.pageSize}
      total={total}
      pageChange={pageChange}
      showTotal={() => `共${range}页/${total}条数据`}
    />
    <Modal title={title} visible={visible} onCancel={() => setVisible(false)} okButtonProps={{
      htmlType: 'submit',
      form: 'form',
    }} destroyOnClose={true} maskClosable={false} >
      <Form name='form' initialValues={initialValues} labelCol={{ span: 8, offset: 0 }} onFinishFailed={(value) => onFinishFailed(value)} wrapperCol={{ span: 16, offset: 0 }} onFinish={(values) => onFinish(values)} >
        <Form.Item name={"announcementBoardName"} label={"公告名称（标题）"} rules={[{ required: true, max: 100, min: 2 }]} >
          <Input placeholder={"请输入公告名称（将展示在APP）"} />
        </Form.Item>
        <Form.Item name={"location"} label={"位置"} rules={[{ required: true }]}  >
          <Select options={location} placeholder={"请选择位置"} mode='multiple' showArrow ></Select>
        </Form.Item>
        <Form.Item name={"jump"} label={"跳转"} rules={[{ required: true }]}  >
          <Select options={jump} placeholder={"请选择页面"} ></Select>
        </Form.Item>
        <Form.Item name={"txt"} label={"备注"} >
          <Input placeholder={"请输入备注（0-30字）"} maxLength={30} />
        </Form.Item>
      </Form>
    </Modal>
  </div>)
}

export default BulletinBoard